<?php

namespace App\Imports;

use App\Http\Models\Business\ExternalOrderDetails;
use App\Http\Models\CategoryContract;
use Exception;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ExternalOrderDetailsImport implements ToCollection, WithHeadingRow
{
    use BaseImportTrait;

    private $required_field = [
        '年份', '客户代码', '物料号', '品类代码', '数量', '金额',
    ];

    private $category_contract_array = [];

    public function collection(Collection $rows)
    {
        foreach ($rows as $key => $row) {
            $row = $row->toArray();

            if ($key === 0) {
                $this->verifyField($row);
                $this->prepareBaseData();
            }

            $this->verifyNotNull($row, $key + 2);
            $this->verifyValueExist($row, $key + 2);

            $this->saveData($row);
        }
    }

    //准备基础数据，用来验证
    private function prepareBaseData()
    {
        $this->category_contract_array = CategoryContract::pluck('id')->toArray();
    }


    //验证字段值存在于数据库基础表中
    private function verifyValueExist(array $row, int $index)
    {
        if (!in_array($row['品类代码'], $this->category_contract_array)) {
            $this->no_error = false;
            $this->error_field = '品类代码';
        }

        if (!$this->no_error) {
            throw new Exception('第 ' . $index . ' 行中的 [' . $this->error_field . '] 的值不存在于系统中！');
        }
    }

    //保存数据
    private function saveData(array $row)
    {
        $model = new ExternalOrderDetails();
        $model->year = $row['年份'];
        $model->payer_code = $row['客户代码'];
        $model->material_code = $row['物料号'];
        $model->category_contract_id = $row['品类代码'];
        $model->quantity = $row['数量'];
        $model->amount = $row['金额'];
        $model->save();
    }
}
